package com.tiku.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tiku.common.ResultJson;
import com.tiku.controller.DTO.TikuDTO;
import com.tiku.entity.ProductSpecifications;
import com.tiku.entity.UserPayTiku;
import com.tiku.mapper.ProductSpecificationsMapper;
import com.tiku.service.UserPayTikuService;
import com.tiku.mapper.UserPayTikuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class UserPayTikuServiceImpl extends ServiceImpl<UserPayTikuMapper, UserPayTiku>
    implements UserPayTikuService{

    @Autowired
    private UserPayTikuMapper userPayTikuMapper;

    @Autowired
    private ProductSpecificationsMapper specificationsMapper;
    @Override
    public Boolean getSpecFlag(String threadLocal, List<ProductSpecifications> selectedSubjects) {
      return getBaseMapper().getSpecFlag(threadLocal,selectedSubjects);


    }

    @Override
    public ResultJson selectList(String userId) {
        List<UserPayTiku> userPayTikus = userPayTikuMapper.selectList(new LambdaQueryWrapper<UserPayTiku>()
                .eq(UserPayTiku::getUserId, userId));
        List<TikuDTO> mapList=new ArrayList<>();
        for (UserPayTiku payTikus : userPayTikus) {
            String paySpecId = payTikus.getPaySpecId();
            ProductSpecifications productSpecifications = specificationsMapper.selectById(paySpecId);
            String specName = productSpecifications.getSpecName();
            Date createTime = payTikus.getCreateTime();
            String specTitle = userPayTikuMapper.getSpecTitle(paySpecId);
            Date endTime=null;
            if (Objects.nonNull(createTime)){
                // 使用 Calendar 来增加一年
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(createTime);
                calendar.add(Calendar.YEAR, 1);  // 增加一年

                // 获取新的 Date 对象
                 endTime = calendar.getTime();
            }

            TikuDTO tikuDTO = new TikuDTO(paySpecId,specName, createTime,specTitle,endTime);
            mapList.add(tikuDTO);
        }
        Map<String, List<TikuDTO>> groupedBySpecTitle = mapList.stream()
                .collect(Collectors.groupingBy(TikuDTO::getSpecTitle));
        List<Map<String, Object>> maps=new ArrayList<>();
        for (String key : groupedBySpecTitle.keySet()) {
            Map<String, Object> a=new HashMap<>();
            a.put("title",key);
            a.put("list",groupedBySpecTitle.get(key));
            maps.add(a);
        }
        return ResultJson.success(maps);


    }
}




